// 菜单权限
import router from '@/router'
import store from '@/store'
import { setSession, getSession } from '@/utils'
import menuApi from '@/api/modules/menu'
import businessApi from '@/api/modules/business'

export function setMeunPermission (hasToken, callback) {
  // 静态菜单权限
  businessApi.getMenuByUserId({
    Authorization: hasToken,
    platform: 'backend',
    projectId: localStorage.projectId
  }).then( async(result) => {
    let data = result.data.map(o => {
      return o.menuUrl
    })
    setSession('permission', data)
    setSession('menuPermission', result.data)
    let roleId = getSession('roleId');
    let isSuperAdmin = store.state.user.isSuperAdmin==='true'
    // 获取动态菜单权限
    menuApi.getCustomMenuByRoleId({
      projectId: store.state.user.projectId,
      roleId: !isSuperAdmin ? roleId[store.state.user.projectId] : '',
      isSuperAdmin
    }).then( async(res) => {
      setSession('customMenuPermission', result.data)
      
      //隐藏 174  检疫疫情   172 消息管理
      let currentType=result.data.filter(item => {
        return ![174].includes(item.id)&&![174].includes(item.parentId)
      })

      const params={ roles: currentType, newroutes: data.indexOf('dataManagement') !== -1 ? res.data : [] }
      const accessRoutes = await store.dispatch('generateRoutes', params )

      router.$addRoutes(accessRoutes)
      newaddRoutes(data, accessRoutes, res.data)
      if (callback) callback()
    })
  })
}

// 设置默认路由
function newaddRoutes(data, routes, mdata){
  let redirectUrl = routes[0].children[0].redirect || '';
  if(data.indexOf('dataManagement') !== -1 && data.indexOf('baseManagement') === -1){
    redirectUrl = `${mdata[0].menuUrl}/index`
  }
  router.addRoutes([{ path: '/', redirect: redirectUrl }])
  // 无效路由，调转到默认路由
  setTimeout(() => {
    router.addRoutes([{ path: '*', redirect: '/', hidden: true }])
  }, 500);
}